@namespace AntDesign
@inherits AntDomComponentBase

<CascadingValue Value="this">
    <div class="@ClassMapper.Class" style="@Style" id="@Id" @ref="Ref">
        @ChildContent
    </div>
</CascadingValue>

@code {

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public bool Disabled { get; set; }

    [Parameter]
    public string ButtonStyle { get; set; } = "outline";

    [Parameter]
    public string Size { get; set; } = "default";

    [Parameter]
    public string Name { get; set; }

    [Parameter]
    public EventCallback<string> OnChange { get; set; }

    [Parameter]
    public string Value { get; set; }

    [Parameter]
    public EventCallback<string> ValueChanged { get; set; }

    internal List<Radio> RadioItems { get; set; } = new List<Radio>();

    string _currentValue => Value;

    protected override async Task OnInitializedAsync()
    {
        string prefixCls = "ant-radio-group";
        ClassMapper.Add(prefixCls)
            .If($"{prefixCls}-large", () => Size == "large")
            .If($"{prefixCls}-small", () => Size == "small")
            .If($"{prefixCls}-solid", () => ButtonStyle == "solid");


        await base.OnInitializedAsync();
    }

    protected override async Task OnParametersSetAsync()
    {
        foreach (var radio in RadioItems)
        {
            if (radio.Value == this._currentValue)
            {
                await radio.Select();
            }
            else
            {
                await radio.UnSelect();
            }
        }
        StateHasChanged();
        await base.OnParametersSetAsync();
    }

    internal async Task AddRadio(Radio radio)
    {
        if (this.Name != null)
        {
            radio._name = Name;
        }
        RadioItems.Add(radio);
        if (this._currentValue == radio.Value)
        {
            await radio.Select();
        }
        StateHasChanged();
    }

    internal async Task OnRadioChange(string value)
    {
        if (this._currentValue != value)
        {
            this.Value = value;
            await this.ValueChanged.InvokeAsync(value);

            foreach (var radio in RadioItems)
            {
                if (radio.Value != this._currentValue)
                {
                    await radio.UnSelect();
                }
            }

            if (this.OnChange.HasDelegate)
            {
                await this.OnChange.InvokeAsync(value);
            }
        }
        StateHasChanged();

    }

}
